import socket
import psutil
import os

def get_network_info():
    """获取网络信息（示例实现）"""
    info = {
        "system": "Windows" if os.name == "nt" else "Linux",
        "hostname": socket.gethostname(),
        "interfaces": [],
        "connections": []
    }
    # 示例：获取网卡信息
    for iface, addrs in psutil.net_if_addrs().items():
        interface_info = {
            "name": iface,
            "is_up": iface in psutil.net_if_stats() and psutil.net_if_stats()[iface].isup,
            "speed": psutil.net_if_stats()[iface].speed if iface in psutil.net_if_stats() else "未知",
            "addresses": {"IPv4": [], "IPv6": [], "MAC": []}
        }
        for addr in addrs:
            if addr.family == socket.AF_INET:
                interface_info["addresses"]["IPv4"].append({
                    "address": addr.address,
                    "netmask": addr.netmask,
                    "broadcast": addr.broadcast
                })
            elif addr.family == socket.AF_INET6:
                interface_info["addresses"]["IPv6"].append({
                    "address": addr.address,
                    "netmask": addr.netmask
                })
            elif addr.family == psutil.AF_LINK:
                interface_info["addresses"]["MAC"].append(addr.address)
        info["interfaces"].append(interface_info)
    return info

def display_network_info():
    """格式化显示网络信息"""
    try:
        info = get_network_info()
    except Exception as e:
        print(f"错误: {str(e)}")
        return

    print(f"系统类型: {info.get('system', '未知')}")
    print(f"主机名称: {info.get('hostname', '未知')}")
    
    print("\n=== 网络接口详情 ===")
    for iface in info.get("interfaces", []):
        print(f"\n接口名称: {iface.get('name', '未知')}")
        print(f"状态: {'已启用' if iface.get('is_up', False) else '已禁用'}")
        print(f"连接速度: {iface.get('speed', '未知')}")
        
        ipv4 = iface.get("addresses", {}).get("IPv4", [])
        if ipv4:
            print("IPv4地址:")
            for addr in ipv4:
                print(f"  - IP地址: {addr.get('address', '未知')}")
                print(f"    子网掩码: {addr.get('netmask', '未知')}")
                print(f"    广播地址: {addr.get('broadcast', '未知')}")
        else:
            print("IPv4地址: 无")
        
        # 类似处理 IPv6 和 MAC 地址...
    
    print("\n=== 网络连接状态 ===")
    connections = info.get("connections", [])
    if connections:
        for conn in connections:
            print(f"\n协议: {conn.get('protocol', '未知')}")
            print(f"本地地址: {conn.get('local', '未知')}")
            print(f"远程地址: {conn.get('remote', '未知')}")
            print(f"状态: {conn.get('status', '未知')}")
            print(f"进程ID: {conn.get('pid', '未知')}")
    else:
        print("未获取到网络连接信息")

if __name__ == "__main__":
    display_network_info()
